import {defineStore} from "pinia"
import {JsonRpcProvider, JsonRpcSigner, Network, Web3Provider} from "@/utils/ethers";
import {formatAddress} from "@/utils/formatters";

type WalletState = {
  _walletAddress: string | undefined,
  _rawProvider: any, // raw provider from the user's wallet, e.g. EIP-1193 provider
  _provider: any, // ethers provider
  _connectStatus: boolean,
  _signer: any, // ethers signer
  _network: any // connected network, derived from provider
}

// State variables
const supportedChainIds = [56, 97]; // chain IDs supported by this app

export default defineStore('wallet', {
  state: (): WalletState => ({
    _rawProvider: undefined,
    _provider: undefined,
    _connectStatus: false,
    _signer: undefined,
    _network: undefined,
    _walletAddress: undefined
  }),
  getters: {
    provider(s): Web3Provider | JsonRpcProvider | undefined {
      return s._provider
    },
    connectStatus(s): boolean {
      return s._connectStatus
    },
    signer(s): JsonRpcSigner | undefined {
      return s._signer
    },
    network(s): Network | undefined {
      return s._network
    },
    walletAddress(s): string | undefined {
      return s._walletAddress
    },
    userDisplayName(s): string {
      return formatAddress(s._walletAddress || '')
    },
    isSupportedNetwork(s): boolean {
      return s._network ? supportedChainIds.includes(s._network.chainId) : true
    }
  },
  actions: {
    setRawProvider(rawProvider: any) {
      this._rawProvider = rawProvider
    },
    setProvider(provider: Web3Provider | JsonRpcProvider | undefined) {
      this._provider = provider
    },
    setConnectStatus(connectStatus: boolean) {
      this._connectStatus = connectStatus
    },
    setSigner(signer: JsonRpcSigner | undefined) {
      this._signer = signer
    },
    setNetwork(network: Network | undefined) {
      this._network = network
    },
    setWalletAddress(wallet: string | undefined) {
      this._walletAddress = wallet
    },

    // Reset state when, e.g.user switches wallets. Provider/signer are automatically updated by ethers so are not cleared
    resetState() {
      this.setProvider(undefined)
      this.setNetwork(undefined)
      this.setConnectStatus(false)
      this.setWalletAddress(undefined)
    },

  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'wallet',
        storage: window.localStorage,
        paths: ['_network', '_walletAddress', '_connectStatus']
      }
    ]
  }
})
